import 'dart:ui';
import 'package:bili_caricature/pages/bloc/widgets/novel_header_widget.dart';
import 'package:bili_caricature/pages/mine/bili_mine/state.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:status_bar_control/status_bar_control.dart';
import '../../../base/base_stateful_page.dart';
import '../../../routers/navigator_utils.dart';
import '../../../widgets/delay_button.dart';
import '../../../widgets/easy_loading.dart';
import '../../bloc/model/cartoon_model_entity.dart';
import '../../bloc/widgets/bottom_content_widget.dart';
import '../../bloc/widgets/des_widget.dart';
import '../../bloc/widgets/recommend_widget.dart';
import '../../bloc/widgets/series_widget.dart';
import 'cubit.dart';

/// 一个bloc完成 局部刷新
const APPBAR_SCROLL_OFFSET = 100;

class BiliMinePage extends BasePage {
  final String imageUrl;

  const BiliMinePage({super.key,required this.imageUrl});

  @override
  BasePageState<BasePage> getState() {
    return _BiliMinePageState();
  }
}

class _BiliMinePageState extends BasePageState<BiliMinePage> {
  @override
  void initState() {
    super.initState();
    isRenderHeader = false;
    pageBgColor = const Color(0xFFF3F4F8);
    _getData();
  }

  /// 请求数据
  _getData() {
    BiliMineCubit biliMineCubit = context.read<BiliMineCubit>();
    biliMineCubit.getAllData();
  }

  _onScroll(offset) {
    /// offset滚动距离
    double alpha = offset / APPBAR_SCROLL_OFFSET;
    if (alpha < 0) {
      alpha = 0;
    } else if (alpha > 1) {
      alpha = 1;
    }

    BiliMineCubit biliMineCubit = context.read<BiliMineCubit>();
    biliMineCubit.changeAppBarAlphaEvent(alpha, offset);
  }

  /// 导航栏
  Widget navWidget(CartoonModelData cartoonModelData, double appBarAlpha, double offset) {
    /// 改变元素透明度,自定义了一个appbar
    return Opacity(
      opacity: appBarAlpha,
      child: Container(
        height: statusBarH + kToolbarHeight,
        alignment: Alignment.center,
        padding: EdgeInsets.only(left: 50.w, right: 50.w, top: 40.h),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
            bottom: BorderSide(width: 1.h, color: Colors.black12),
          ),
        ),
        child: Row(
          children: [
            Container(
              width: offset >= 150.h ? 1.sw - 150.w : 1.sw - 110.w,
              margin: EdgeInsets.only(right: 10.w),
              child: Text(
                cartoonModelData.title,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(fontSize: 15.sp),
              ),
            ),
            Visibility(
              visible: offset >= 150.h ? true : false,
              child: Container(
                alignment: Alignment.center,
                width: 40.w,
                height: 20.h,
                decoration: BoxDecoration(
                    color: Colors.orange,
                    border: Border.all(width: 1.w, color: Colors.orange),
                    borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(6.h), bottomRight: Radius.circular(6.h))),
                child: Text(
                  '追书',
                  style:
                      TextStyle(color: Colors.white, fontSize: 12.sp, fontWeight: FontWeight.w500),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 返回按钮
  Widget backBtn(double appBarAlpha) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        DelayButton(
          width: 48.w,
          margin: EdgeInsets.only(top: 20.h),
          height: ScreenUtil().statusBarHeight + kToolbarHeight,
          onTap: () {
            XsEasyLoading.showToast('不要再点了,已经是首页了');
          },
          mainWidget: Align(
            child: Image.asset("assets/images/back_black.png",
                fit: BoxFit.cover,
                color: appBarAlpha == 1 ? Colors.black : Colors.white,
                width: 26.w,
                height: 30.w),
          ),
        ),
        DelayButton(
          width: 48.w,
          margin: EdgeInsets.only(top: 20.h),
          height: ScreenUtil().statusBarHeight + kToolbarHeight,
          onTap: () {
            StatusBarControl.setStyle(StatusBarStyle.DARK_CONTENT);
          },
          mainWidget: Align(
            child: Image.asset("assets/images/ZCIcon_share_normal@3x.png",
                fit: BoxFit.cover,
                color: appBarAlpha == 1 ? Colors.black : Colors.white,
                width: 26.w,
                height: 26.w),
          ),
        ),
      ],
    );
  }

  /// 底部widget
  Widget bottomWidget(BiliMineState state) {
    return Positioned(
        left: 0,
        bottom: bottomSafeBarH,
        child: BottomContentWidget(
          epList: state.mainModel!.ep,
        ));
  }

  void _listener(BuildContext context, BiliMineState state) {
    if (state.appBarAlpha == 0) {
      StatusBarControl.setStyle(StatusBarStyle.LIGHT_CONTENT);
    } else if (state.appBarAlpha == 1) {
      StatusBarControl.setStyle(StatusBarStyle.DARK_CONTENT);
    }
  }

  Widget mainPageWidget() {
    return Stack(
      children: [
        BlocBuilder<BiliMineCubit, BiliMineState>(
          buildWhen: (previous, current) {
            return previous.isRefreshMainView == true;
          },
          builder: (context, state) {
            return resultWidget(
              state,
              (baseState, context) => MediaQuery.removePadding(
                removeTop: true, //移除上部
                context: context,
                //监听滚动
                child: NotificationListener(
                  onNotification: (scrollNotification) {
                    if (scrollNotification is ScrollUpdateNotification &&
                        scrollNotification.depth == 0) {
                      //发生滚动并且是第0个元素
                      _onScroll(scrollNotification.metrics.pixels);
                    }
                    return false;
                  },
                  child: Container(
                    color: Colors.white,
                    margin: EdgeInsets.only(bottom: bottomSafeBarH),
                    child: ListView(
                      physics: const ClampingScrollPhysics(),
                      children: [
                        /// 头部widget
                        NovelHeaderWidget(
                          model: state.mainModel ?? CartoonModelData(),
                          imageUrl: widget.imageUrl,
                          type: 1,
                        ),

                        /// 描述widget
                        DesWidget(
                          model: state.mainModel ?? CartoonModelData(),
                        ),

                        /// 同系列widget
                        const SeriesWidget(
                          type: 1,
                        ),

                        /// 推荐widget
                        const RecommendWidget(
                          type: 1,
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            );
          },
        ),

        /// 子节点刷新,不刷新根节点
        BlocConsumer<BiliMineCubit, BiliMineState>(
          builder: (context, navState) {
            return resultWidget(
                navState,
                (baseState, context) => navWidget(navState.mainModel ?? CartoonModelData(),
                    navState.appBarAlpha, navState.offset));
          },
          listener: _listener,
          listenWhen: (state1, state2) {
            if ((state1.offset >= 50.h) || (state2.offset == 0)) {
              return true;
            }
            return false;
          },
        ),

        /// 子节点刷新,不刷新根节点
        BlocBuilder<BiliMineCubit, BiliMineState>(
          builder: (context, navState) {
            return resultWidget(navState, (baseState, context) => backBtn(navState.appBarAlpha));
          },
        ),
        Positioned(
            child: Center(
          child: Container(
            alignment: Alignment.center,
            height: 60.h,
            padding: EdgeInsets.all(5.w),
            width: 1.sw - 100.w,
            color: Colors.blue,
            child: const Text(
              '单页面多接口并发请求+局部刷新(使用一个bloc)案例',
              style: TextStyle(color: Colors.white),
            ),
          ),
        ))
      ],
    );
  }

  @override
  Widget buildPage(BuildContext context) {
    return mainPageWidget();
  }
}
